import React from 'react';
import {routerRedux} from 'dva/router';
import {Layout, Menu, notification, Icon, Tabs, Dropdown, Tooltip, TreeSelect, Typography} from 'antd';
import find from 'lodash/find';
import DocumentTitle from 'react-document-title';
import isEqual from 'lodash/isEqual';
import memoizeOne from 'memoize-one';
import {connect} from 'dva';
import {ContainerQuery} from 'react-container-query';
import classNames from 'classnames';
import config from '@/config/config';
import uuid from 'uuid-js';
import union from '../images/union.png';
import Header from './Header';
import themeObj from './../pages/Home/chalk.json';

const {Paragraph} = Typography;
const {TreeNode} = TreeSelect;
const {TabPane} = Tabs;
const {SubMenu} = Menu;
const {Content, Sider} = Layout;
import echarts from 'echarts';

echarts.registerTheme('my_theme', themeObj);

// Conversion router to menu.
function formatter(data, parentAuthority, parentName) {
  return data
    .map(item => {
      let locale = 'menu';
      if (parentName && item.name) {
        locale = `${parentName}.${item.name}`;
      } else if (item.name) {
        locale = `menu.${item.name}`;
      } else if (parentName) {
        locale = parentName;
      }
      if (item.path) {
        const result = {
          ...item,
          locale,
          authority: item.authority || parentAuthority,
        };
        if (item.routes) {
          const children = formatter(item.routes, item.authority, locale);
          // Reduce memory usage
          result.children = children;
        }
        delete result.routes;
        return result;
      }

      return null;
    })
    .filter(item => item);
}

const memoizeOneFormatter = memoizeOne(formatter, isEqual);

const query = {
  'screen-xs': {
    maxWidth: 575,
  },
  'screen-sm': {
    minWidth: 576,
    maxWidth: 767,
  },
  'screen-md': {
    minWidth: 768,
    maxWidth: 991,
  },
  'screen-lg': {
    minWidth: 992,
    maxWidth: 1199,
  },
  'screen-xl': {
    minWidth: 1200,
    maxWidth: 1599,
  },
  'screen-xxl': {
    minWidth: 1600,
  },
};

class BasicLayout extends React.PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      uuid: uuid.create().hex,
      IsFull: this.IsFull(),
      rendering: true,
      isMobile: false,
      collapsed: localStorage.getItem('collapsed') === '2',
      spin: false,
      meter_reading: find(this.permissions, {name: 'meter_overview'}) ||
        find(this.permissions, {name: 'meter_analysis'}) ||
        find(this.permissions, {name: 'meter_management'}) ||
        find(this.permissions, {name: 'meter_abnormal_analysis'}) ||
        find(this.permissions, {name: 'meter_vendor_analysis'}),
      revenue: find(this.permissions, {name: 'jump_revenue'}) ||
        find(this.permissions, {name: 'price_nature'}) ||
        find(this.permissions, {name: 'owner_information'}) ||
        find(this.permissions, {name: 'payment_record'}) ||
        find(this.permissions, {name: 'regions_management'}) ||
        find(this.permissions, {name: 'user_report'}),
      user: find(this.permissions, {name: 'branch_management'}) ||
        find(this.permissions, {name: 'user_management'}) ||
        find(this.permissions, {name: 'role_management'}),
      smartGIS: find(this.permissions, {name: 'pipe_network_overview'}) ||
        find(this.permissions, {name: 'pressure_sensor_view'}) ||
        find(this.permissions, {name: 'waterworks_device'}) ||
        find(this.permissions, {name: 'workstation_view'}),
      inspect: find(this.permissions, {name: 'issue_management'}) ||
        find(this.permissions, {name: 'available_issue'}) ||
        find(this.permissions, {name: 'personal_issue'}) ||
        find(this.permissions, {name: 'inspector_statistics'}),
      oa: find(this.permissions, {name: 'structure'}) ||
        find(this.permissions, {name: "department_management"}) ||
        find(this.permissions, {name: "personnel_management"}) ||
        find(this.permissions, {name: "leave_summary"}) ||
        find(this.permissions, {name: "leave_apply"}) ||
        find(this.permissions, {name: "leave_record"}) ||
        find(this.permissions, {name: "release_notice"}) ||
        find(this.permissions, {name: "contact_person"}) ||
        find(this.permissions, {name: "public_file"}),
      wechat: find(this.permissions, {name: 'wechat_menu'}) ||
        find(this.permissions, {name: 'wechat_notice'}),
      erp: find(this.permissions, {name: 'warehouse'}) ||
        find(this.permissions, {name: 'warehouse_edit'}) ||
        find(this.permissions, {name: 'supplier'}) ||
        find(this.permissions, {name: 'supplier_edit'}) ||
        find(this.permissions, {name: 'material'}) ||
        find(this.permissions, {name: 'material_edit'}) ||
        find(this.permissions, {name: 'inventory_statistics'}) ||
        find(this.permissions, {name: 'warehousing'}) ||
        find(this.permissions, {name: 'warehousing_operation'}) ||
        find(this.permissions, {name: 'outbound'}) ||
        find(this.permissions, {name: 'outbound_operation'}) ||
        find(this.permissions, {name: 'inventory'}) ||
        find(this.permissions, {name: 'inventory_operation'}),
      party: find(this.permissions, {name: 'party_homepage'}) ||
        find(this.permissions, {name: 'article_management'}) ||
        find(this.permissions, {name: 'organization_management'}) ||
        find(this.permissions, {name: 'party_member_management'}) ||
        find(this.permissions, {name: 'development_party_member_management'})
    };
  }

  // 判断是否全屏
  IsFull = () => {
    const fullscreenElement = document.fullscreenElement || document.mozFullscreenElement || document.webkitFullscreenElement;
    const fullscreenEnabled = document.fullscreenEnabled || document.mozFullscreenEnabled || document.webkitFullscreenEnabled;
    if (fullscreenElement == null) {
      return false;
    }
    return true;

  };

  componentDidMount() {
    console.log('this.initPathName', this.initPathName);
    const {dispatch} = this.props;
    dispatch({
      type: 'user/fetchCurrent',
    });
    dispatch({
      type: 'setting/getSetting',
    });
    dispatch({
      type: 'global/getGridTableW',
    });
    window.addEventListener('resize', this.resizeChart);
    const that = this;
    return;
    notification.info({
      message: '收到新通知',
      duration: 0,
      placement: 'bottomRight',
      description: <div>
        <Paragraph>
          关于水价调整相关通知，请认真阅读
        </Paragraph>
        <a style={{float: 'right'}} href="javascript:;" onClick={() => {
          that.handleClick({key: '/webMail'});
        }}>查看详情</a>
      </div>,
    });

    let ws = window.ws = new WebSocket(`${config.wsPrefix}/events?token=Bearer ${sessionStorage.getItem('token')}`);
    ws.onopen = function (ev) {
      console.log('-----------');
      console.log('[Connected]');
      console.log('-----------');
      that.wsTimer = setInterval(function () {
        ws.send('try connect');
      }, 10000);
    };

    ws.onclose = function (ev) {
      console.log('--------------');
      console.log('[Disconnected]');
      console.log('--------------');
      if (that.wsTimer) {
        clearInterval(that.wsTimer);
      }
    };
    ws.onmessage = function (ev) {
      var payload = JSON.parse(ev.data);
      const {task_id} = that.props;
      if (payload.status_code === 200) {
        if (payload.data.event === 'command_callback') {
          if (task_id == payload.data.task_id) {
            console.log('两者id一致');
            switch (Number(payload.data.status)) {
              case 1:
                console.log('即时指令下发成功');
                window.modal.update({
                  content: `即时指令下发成功`,
                  icon: <Icon type="check-circle"/>,
                  className: '',
                });
                break;
              case 2:
                window.modal.update({
                  content: `离线指令下发成功`,
                  icon: <Icon type="check-circle"/>,
                  className: '',
                });
                console.log('离线指令下发成功');
                break;
              case 3:
                console.log('指令下发失败');
                window.modal.update({
                  icon: <Icon type="close-circle" style={{color: 'red'}}/>,
                  content: `指令下发失败`,
                  className: '',
                });
                break;
            }
          }

        }
      }
    };


  }


  getContext() {
    const {location} = this.props;
    return {
      location,
    };
  }


  handleClick = (e) => {
    console.log('click ', e);
    const {panes, routerMapping, dispatch} = this.props;
    const activeKey = e.key;
    if (e.key.indexOf('blank_') >= 0) {
      console.log('跳转到其它页面');
      window.open('http://47.103.146.199:8085/front/views/index.html', '_blank');
      return false;
    }
    if (find(panes, o => o.key == activeKey)) {
      console.log('已经存在');
    } else {
      if (find(routerMapping, o => o.path == activeKey)) {
        panes.push({
          title: find(routerMapping, o => o.path == activeKey).name,
          content: 'New Tab Pane',
          key: activeKey,
        });
      }

    }
    dispatch(routerRedux.push(activeKey));
    dispatch({
      type: 'global/changePanesAndActive',
      payload: {panes, activeKey},
    });
    // this.setState({ panes, activeKey });
  };

  onChange = activeKey => {
    console.log('activeKey', activeKey);
    const {dispatch} = this.props;
    dispatch(routerRedux.push(activeKey));
    dispatch({
      type: 'global/changePanesAndActive',
      payload: {activeKey},
    });
    // this.setState({ activeKey });
  };

  onEdit = (targetKey, action) => {
    this[action](targetKey);
  };

  remove = targetKey => {
    let {activeKey, routerMapping} = this.props;
    console.log(activeKey);
    let lastIndex;
    this.props.panes.forEach((pane, i) => {
      if (pane.key === targetKey) {
        lastIndex = i - 1;
      }
    });
    const panes = this.props.panes.filter(pane => pane.key !== targetKey);
    if (panes.length && activeKey === targetKey) {
      if (lastIndex >= 0) {
        activeKey = panes[lastIndex].key;
      } else {
        activeKey = panes[0].key;
      }
    }
    const model = find(routerMapping, o => o.path == targetKey);
    const {dispatch} = this.props;
    dispatch({
      type: 'global/changePanesAndActive',
      payload: {panes, activeKey},
    });
    // this.setState({ panes, activeKey });
    dispatch(routerRedux.push(activeKey));
    if (model) {
      this.closeTab(model);
    }

  };

  closeTab = (model) => {
    const {dispatch} = this.props;
    if (model.modelName) {
      dispatch({
        type: `${model.modelName}/reset`,
      });
    }
  };

  resizeChart = () => {
    this.setState({
      IsFull: this.IsFull(),
    });
    const {dispatch} = this.props;
    dispatch({
      type: 'global/getGridTableW',
    });
  };

  componentWillUnmount() {
    window.removeEventListener('resize', this.resizeChart);
  }

  handleMenuClick = (item) => {
    const {dispatch, routerMapping} = this.props;
    const that = this;
    if (item.key === '1') {
      console.log('刷新当前');
      const model = find(routerMapping, o => o.path == this.props.activeKey);
      console.log('model', model);

      if (model.modelName) {
        dispatch({
          type: `${model.modelName}/${(this.props[model.modelName] && this.props[model.modelName].detail && this.props[model.modelName].detail.isDetail) ? 'resetDetail' : 'reset'}`,
          payload: true,
          callback: () => {
            that.setState({
              uuid: uuid.create().hex,
            }, () => {
              console.log('uuid', that.state.uuid);
              dispatch({
                type: `${model.modelName}/${(this.props[model.modelName] && this.props[model.modelName].detail && this.props[model.modelName].detail.isDetail) ? 'fetchDetail' : 'fetch'}`,
              });
            });
          },
        });
      }
    } else if (item.key == '2') {
      console.log('this.props.panes', this.props.panes);
      for (let i = 0; i < this.props.panes.length; i++) {
        const model = find(routerMapping, o => o.path == this.props.panes[i].key);
        console.log('model', model);
        if (model) {
          this.closeTab(model);
        }
      }
      // this.setState({
      //   activeKey: '/home',
      //   panes: [{ title: '主页', key: '/home' }],
      // });
      dispatch({
        type: 'global/changePanesAndActive',
        payload: {
          activeKey: '/dashboard',
          panes: [{title: '系统总览', key: '/dashboard'}],
        },
      });
      dispatch(routerRedux.push('/dashboard'));
    } else if (item.key == '3') {

      for (let i = 0; i < this.props.panes.length; i++) {
        if (this.props.panes[i].key !== this.props.activeKey) {
          const model = find(routerMapping, o => o.path == this.props.panes[i].key);
          console.log('model', model);
          if (model) {
            this.closeTab(model);
          }
        }
      }
      const new_panes = this.props.panes.filter((item, index) => item.key === '/dashboard' || item.key === that.props.activeKey);
      console.log('new_panes', new_panes);
      dispatch({
        type: 'global/changePanesAndActive',
        payload: {panes: new_panes},
      });
      // this.setState({
      //   panes: new_panes,
      // });
    }
  };

  render() {
    const {
      navTheme,
      layout: PropsLayout,
      children,
      location: {pathname},
      activeKey,
    } = this.props;
    const menu = (
      <Menu onClick={this.handleMenuClick}>
        <Menu.Item key="1">刷新当前</Menu.Item>
        <Menu.Item key="2">关闭全部</Menu.Item>
        <Menu.Item key="3">除此之外全部关闭</Menu.Item>
      </Menu>
    );
    console.log('activeKey', activeKey);
    let darkTab = false;
    if (activeKey === '/home' || activeKey === '/dashboard' || activeKey === '/revenue') {
      darkTab = true;
    }

    const operations = <div>
      <div
        onClick={() => {
          const that = this;
          this.setState({
            spin: true,
          });
          this.handleMenuClick({key: '1'});
          setTimeout(() => {
            that.setState({
              spin: false,
            });
          }, 800);
        }
        }
        style={{
          display: 'inline-block',
          borderLeft: '1px solid #565656',
          padding: '0 10px',
          color: '#fff',
          cursor: 'pointer',
        }}
      >
        刷新 <Icon type="reload" spin={this.state.spin} style={{fontSize: '12px'}}/>
      </div>
      <Dropdown overlay={menu}>
        <div style={{
          borderLeft: '1px solid #565656',
          borderRight: '1px solid #565656',
          padding: '0 10px',
          cursor: 'auto',
          display: 'inline-block',
          color: '#fff',
        }}
        >
          页面操作<Icon type="down"/>
        </div>
      </Dropdown>
      <Icon
        type={this.state.IsFull ? 'fullscreen-exit' : 'fullscreen'}
        style={{padding: '0 10px', color: '#fff', cursor: 'pointer'}}
        onClick={() => {
          const element = document.documentElement;
          if (this.state.IsFull) {
            if (document.exitFullscreen) {
              document.exitFullscreen();
            } else if (document.mozCancelFullScreen) {
              document.mozCancelFullScreen();
            } else if (document.webkitExitFullscreen) {
              document.webkitExitFullscreen();
            }
          } else if (element.requestFullscreen) {
            element.requestFullscreen();
          } else if (element.msRequestFullscreen) {
            element.msRequestFullscreen();
          } else if (element.mozRequestFullScreen) {
            element.mozRequestFullScreen();
          } else if (element.webkitRequestFullscreen) {
            element.webkitRequestFullscreen();
          }
        }}
      />
    </div>;
    const HeartSvg = () => (
      <svg t="1620181317810" className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
           p-id="2007" width="16" height="18">
        <path
          d="M512.284444 57.059556C747.178667 145.066667 889.742222 426.666667 767.601778 654.734222L469.617778 355.384889l113.777778-114.119111-71.111112-70.769778c-39.253333 38.4-101.603556 46.648889-143.701333 29.639111L142.108444 426.723556l128.284445 127.772444 85.447111-85.105778 297.870222 298.837334c-145.749333 80.042667-347.818667 54.784-496.924444-100.124445l-72.248889 72.021333c21.674667 29.980444 39.822222 57.173333 62.350222 79.928889a89.656889 89.656889 0 0 1-8.305778 7.566223c-3.754667-0.568889-8.248889-2.048-12.231111-2.048-38.4 0-69.461333 33.393778-69.461333 71.850666C56.888889 935.822222 88.177778 967.111111 126.634667 967.111111c38.4 0 71.338667-31.573333 71.338666-69.973333 0-4.551111-1.024-8.590222-1.820444-12.8l11.093333-10.922667c171.406222 115.598222 359.310222 130.048 561.493334 9.102222l83.456 83.740445 114.289777-112.753778-84.024889-84.878222C1123.555556 405.276444 802.133333 48.355556 512.284444 57.059556"
          fill="#FF0000" p-id="2008"></path>
      </svg>
    );
    const HeartSvg2 = () => (
      <svg t="1619410341098" className="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
           p-id="8808" width="20" height="20">
        <path
          d="M403.508966 633.697103c63.081931 39.777103 129.836138 41.772138 198.532413 3.372138l2.754207-1.624275 31.567448 31.673379 50.864552-50.193655-31.638069-31.955862 3.760552-6.179311c70.779586-122.473931-23.869793-263.220966-147.42069-259.531034h-35.098482l33.032827 12.411586 5.420138 2.136276c78.653793 32.785655 121.096828 123.621517 89.335172 197.420138l-0.971034 2.065655-98.092138-98.515862 41.613241-41.754483-35.027862-34.85131-4.519724 4.413793c-11.74069 11.511172-31.602759 15.165793-45.673931 9.480827l-3.919448-1.588965-90.323862 90.394483 55.966896 55.737379 31.214345-31.161379 98.162759 98.462896-3.213242 1.483035c-51.835586 22.192552-116.206345 7.944828-163.080827-40.730483l-4.519724-4.678621-34.904276 34.763035 13.241379 18.361379 3.531035 4.678621 2.295172 2.824827-1.800827 0.317793c-14.459586 3.10731-25.405793 16.525241-25.405794 32.008828a31.955862 31.955862 0 0 0 31.920552 31.867586c16.525241 0 30.596414-12.711724 32.308966-28.74262l0.088276-2.365794z"
          fill="#ffffff" p-id="8809"></path>
        <path
          d="M512 134.391172C303.457103 134.391172 134.408828 303.474759 134.408828 512c0 208.542897 169.048276 377.608828 377.591172 377.608828 208.542897 0 377.608828-169.065931 377.608828-377.608828 0-208.542897-169.065931-377.591172-377.608828-377.591172z m0 64.017656c173.197241 0 313.608828 140.393931 313.608828 313.591172S685.197241 825.608828 512 825.608828c-173.197241 0-313.591172-140.411586-313.591172-313.608828 0-173.197241 140.393931-313.591172 313.591172-313.591172z"
          fill="#ffffff" p-id="8810"></path>
      </svg>
    )
    const HeartIcon = props => <Icon component={HeartSvg} {...props} />;
    const HeartIcon2 = props => <Icon component={HeartSvg2} {...props} />;
    const that = this;
    const username = sessionStorage.getItem('username');
    let branch_id = sessionStorage.getItem('branch_id');

    const layout = (
      <div style={{height: '100vh'}}>
        <Header/>
        <Layout style={{height: 'calc(100vh - 56px)'}}>
          <div
            style={{left: this.state.collapsed ? 0 : `${200}px`}}
            onClick={() => {
              this.setState({
                collapsed: !this.state.collapsed,
              }, function () {
                localStorage.setItem('collapsed', this.state.collapsed ? '2' : '1');
                setTimeout(function () {
                  const {dispatch} = that.props;
                  dispatch({
                    type: 'global/getGridTableW',
                  });
                }, 300);
              });

            }}
            className="open_shrink"
            title="展开/收起"
          >
            <span>
              <Icon type={this.state.collapsed ? 'caret-right' : 'caret-left'} style={{color: '#fff'}}/>
            </span>
          </div>
          <Sider
            width={this.state.collapsed ? 0 : 200}
            className='body-sidar'
          >

            <h3 style={{color: '#ccc', fontSize: '14px', padding: '10px 0px 0px 25px'}}>导航菜单</h3>
            <Menu
              theme="dark"
              mode="inline"
              style={{height: 'calc(100vh - 110px)'}}
              onClick={this.handleClick}
              selectedKeys={[this.props.activeKey]}
              defaultOpenKeys={['sub0', 'sub11', 'sub52']}
            >
              {
                (find(this.permissions, {name: '集中器列表'}) || find(this.permissions, {name: '集中器固件列表'})) &&
                <SubMenu
                  key="sub0"
                  title={
                    <span>
              <Icon type="cloud-server"/>
                <span>集中器管理</span>
              </span>
                  }
                >
                  {
                    find(this.permissions, {name: '集中器列表'}) &&
                    <Menu.Item key="/concentrators"><Icon type="tags"/>集中器列表</Menu.Item>
                  }
                  {
                    find(this.permissions, {name: '集中器固件列表'}) &&
                    <Menu.Item key="/concentrator_firmwares"><Icon type="tags"/>集中器固件列表</Menu.Item>
                  }

                </SubMenu>
              }


              {
                (find(this.permissions, { name: '账号管理' })||  find(this.permissions, { name: '账号管理' }))&&
                <SubMenu
                  key="sub52"
                  title={
                    <span>
             <Icon type="team"/>
                <span>账号角色</span>
              </span>
                  }
                >
                  {
                    find(this.permissions, { name: '账号管理' })&&
                    <Menu.Item key="/staffs"><Icon type="solution"/>账号管理</Menu.Item>
                  }
                  {
                    find(this.permissions, { name: '角色管理' })&&
                    <Menu.Item key="/roles"><Icon type="solution"/>角色管理</Menu.Item>
                  }
                </SubMenu>

              }

            </Menu>
          </Sider>
          <Layout>
            <Content className={'dark_tabs'}>
              {
                activeKey !== '/dashboard' &&
                <Tabs

                  hideAdd
                  onChange={this.onChange}
                  activeKey={this.props.activeKey}
                  onEdit={this.onEdit}
                  type="editable-card"
                  tabBarExtraContent={operations}
                >
                  {this.props.panes.map(pane => (
                    <TabPane tab={pane.title} key={pane.key}/>
                  ))}
                </Tabs>
              }

              <div className="outter-box" style={{
                height: activeKey === '/dashboard' ? 'calc(100vh - 56px)' : 'calc(100vh - 98px)',
                overflow: 'auto'
              }}
                   key={this.state.uuid}>
                {children}
              </div>
            </Content>
          </Layout>
        </Layout>
      </div>
    );
    return (
      <React.Fragment>
        <DocumentTitle title="珠华水工业集中器管理平台">
          <ContainerQuery query={query}>
            {params => (
              <div className={classNames(params)}>

                {layout}
              </div>
            )}
          </ContainerQuery>
        </DocumentTitle>
        {/*  {this.renderSettingDrawer()} */}
      </React.Fragment>
    );
  }
}

export default connect(({global, devices, setting}) => ({
  collapsed: global.collapsed,
  layout: setting.layout,
  devices: devices,
  task_id: global.task_id,
  activeKey: global.activeKey,
  routerMapping: global.routerMapping,
  panes: global.panes,
  ...setting,
}))(BasicLayout);
